package com.zte.shopping.service.impl;

import com.zte.shopping.action.backend.BackendLoginController;
import com.zte.shopping.constant.DictConstant;
import com.zte.shopping.constant.StatusConstant;
import com.zte.shopping.entity.Product;
import com.zte.shopping.entity.ProductType;
import com.zte.shopping.entity.Sequence;
import com.zte.shopping.mapper.product.ProductMapper;
import com.zte.shopping.mapper.sequence.SequenceMapper;
import com.zte.shopping.service.ProductService;
import com.zte.shopping.service.ProductTypeService;
import com.zte.shopping.util.Constants;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @program: ssm
 * @description: productService 商品
 * @author: zuti
 * @create: 2020-06-28 17:02
 **/
@Service
public class ProductServiceImpl implements ProductService {

    private  static  final Logger logger= Logger.getLogger(ProductServiceImpl.class);
    @Autowired
    ProductMapper productMapper;
    @Autowired
    SequenceMapper sequenceMapper;

    /**
     * @param pageIndex
     * @return java.util.List<com.zte.shopping.entity.ProductType>
     * @Author zuti
     * @Description //TODO 查询商品列表
     * @Date 17:04 2020/6/28
     * @Param [pageIndex]
     */
    @Override
    public List<Product> productList(Integer pageIndex) {
        int pageSize = Constants.pageSize;
        int from = (pageIndex-1)*pageSize;
        logger.debug("enter ProductServiceImpl ------> productList param: pageIndex="+pageIndex+" pageSize="+pageSize+" from="+from);
        return productMapper.productList(from,pageSize);
    }

    /**
     * @return int
     * @Author zuti
     * @Description //TODO 查询所有商品数量
     * @Date 17:05 2020/6/28
     * @Param []
     **/
    @Override
    public int productListCount() {
        logger.debug("enter ProductServiceImpl ------> productListCount()");
        return productMapper.productListCount();
    }

    /**
     * @Author zuti
     * @Description //TODO 根据商品Id来查询这个商品是否存在
     * @Date 14:02 2020/6/30
     * @Param [id]
     * @return com.zte.shopping.entity.Product
     **/
    @Override
    public Product findById(String id) {
        return productMapper.selectById(Integer.parseInt(id));
    }

    /**
     * @Author zuti
     * @Description //TODO 后台修改产品信息
     * @Date 14:02 2020/6/30
     * @Param [file, productId, name, price, typeId, session]
     * @return void
     **/
    @Override
    public void modifyProduct(CommonsMultipartFile file, String productId, String name, String price, String typeId, HttpSession session) throws FileUploadException {
        Product product = new Product();
        product.setProductId(Integer.parseInt(productId));
        product.setName(name);
        product.setPrice(Double.parseDouble(price));

        ProductType type = new ProductType();
        type.setId(Integer.parseInt(typeId));

        product.setProductType(type);

        String path = "/upload/" + new SimpleDateFormat("yyyyMMdd").format(new Date());
        String cp = session.getServletContext().getRealPath(path);
        String originalFilename = file.getOriginalFilename();

        // 解决当会员在修改商品时  没有 修改商品的图片的bug
        String image = "";
        if (originalFilename != null && "".equals(originalFilename))
        {
            Product pro = productMapper.selectById(Integer.parseInt(productId));

            if (pro != null)
            {
                String imageStr = pro.getImage();

                image = path + "/" + imageStr.substring(imageStr.lastIndexOf("/") + 1, imageStr.length());
            }
        }else
        {
            image = path + "/" + originalFilename;
        }


        product.setImage(image);

        productMapper.updateProduct(product);

        File f = new File(cp);
        f.mkdirs();

        try
        {
            file.transferTo(new File(cp, originalFilename));
        } catch (IllegalStateException e)
        {
            throw new FileUploadException("文件上传出错", e);
        } catch (IOException e)
        {
            throw new FileUploadException("文件上传出错", e);
        }


    }

    /**
     * @Author zuti
     * @Description //TODO 后台删除商品
     * @Date 14:02 2020/6/30
     * @Param [id]
     * @return void
     **/
    @Override
    public void removeById(String id) {
        productMapper.deleteById(Integer.parseInt(id));
    }

    /**
     * @Author zuti
     * @Description //TODO 后台添加商品
     * @Date 14:03 2020/6/30
     * @Param [file, productNo, productName, price, typeId, session]
     * @return void
     **/
    @Override
    public void addProduct(CommonsMultipartFile file, String productNo, String productName, String price, String typeId, HttpSession session) throws FileUploadException {
        Product product = new Product();
        product.setProductNo(productNo);
        product.setName(productName);
        product.setPrice(Double.parseDouble(price));

        ProductType type = new ProductType();
        type.setId(Integer.parseInt(typeId));
        product.setProductType(type);

        /**
         标识符  + 年月日  + 序列号

         标识符:例如:商品--SP
         年月日:年月日--20180106
         序列号:000001--999999
         第一个编号序列号为000001
         当编号达到了999999,则下一个编号重置为000001
         序列号信息保存在sys_sequence表中

         id
         name		标识符		SP
         value		同一个标识符只对应一个值
         假如当前的SP值为0000001
         如果新增一个新的商品,则同步修改sequence表中的数据,将其值改为000002
         */
        // DictConstant.PRODUCT_NO_PREFIX表示 商品编号前缀 :SP
        Sequence sequence = sequenceMapper.selectByName(DictConstant.PRODUCT_NO_PREFIX);

        if (sequence == null)
        {
            // 如果没有查找到对应的Sequence信息  则表示此时尚未使用商品编号
            // 初始化商品编号的序列号值为最小,即000001
            Sequence sequ = new Sequence();

            // 设置 商品编号前缀: SP
            sequ.setName(DictConstant.PRODUCT_NO_PREFIX);

            // 设置 商品编号的序列号最小值为000001
            sequ.setValue(DictConstant.PRODUCT_NO_SEQUENCE_MIN);

            sequenceMapper.insertSequence(sequ);

            //  标识符  + 年月日 + 序列号
            product.setProductNo(DictConstant.PRODUCT_NO_PREFIX + new SimpleDateFormat("yyyyMMdd").format(new Date()) + sequ.getValue());
        }else
        {
            String value = sequence.getValue();

            // 若当前的序列号达到了最大值,则初始化设置为最小值,从头开始
            if (DictConstant.PRODUCT_NO_SEQUENCE_MAX.equals(value))
            {
                value = DictConstant.PRODUCT_NO_SEQUENCE_MIN;
            }else
            {
                value = String.format("%06d", Integer.parseInt(value) + 1);
            }

            sequenceMapper.updateSquenceValue(DictConstant.PRODUCT_NO_PREFIX, value);
        }

        String path = "/upload/" + new SimpleDateFormat("yyyyMMdd").format(new Date());
        String cp = session.getServletContext().getRealPath(path);
        String orifileName = file.getOriginalFilename(); // 原始文件名

        product.setImage(path + "/" + orifileName);

        // 先做添加商品
        productMapper.insertProduct(product);

        // 上传商品图片到服务器
        File f = new File(cp);
        f.mkdirs();

        try
        {
            file.transferTo(new File(cp, orifileName));
        } catch (IllegalStateException e)
        {
            // org.apache.commons.fileupload.FileUploadException 不是自定义异常
            throw new FileUploadException("文件上传出错", e);
        } catch (IOException e)
        {
            throw new FileUploadException("文件上传出错", e);
        }
    }

    /**
     * @param pageIndex
     * @param minPrice
     * @param maxPrice
     * @param productTypeId
     * @return java.util.List<com.zte.shopping.entity.Product>
     * @Author zuti
     * @Description //TODO 前台搜索商品，参数为价格区间，产品类型
     * @Date 14:05 2020/6/30
     * @Param [pageIndex, minPrice, maxPrice, productTypeId]
     */
    @Override
    public List<Product> findProductByParamList(Integer pageIndex, Integer minPrice, Integer maxPrice, Integer productTypeId) {
        //查询的商品类型为有效
        Integer status = StatusConstant.PRODUCT_TYPE_STATUS_ENABLE;
        //设置分页信息
        int pageSize = Constants.pageSize;
        int from = (pageIndex-1)*pageSize;

        logger.debug("enter ProductServiceImpl ------> indProductByParamList 向下传递的参数 param: minPrice="+minPrice
                    +" maxPrice="+maxPrice+" productTypeId="+productTypeId+" status="+status+" from="+from+" pageSize="+pageSize);

        //查询产品列表
        List<Product> productList = productMapper.selectByParamList(minPrice,maxPrice,productTypeId,status,from,pageSize);
        logger.debug("enter ProductServiceImpl ------> indProductByParamList result: productList");
        for(int i=0;i<productList.size();i++){
            Product p = productList.get(i);
            logger.debug("product"+i+" name="+p.getName());
        }
        return productList;
    }

    @Override
    public int productListCountByParam(Integer minPrice, Integer maxPrice, Integer productTypeId) {

        //查询的商品类型为有效
        Integer status = StatusConstant.PRODUCT_TYPE_STATUS_ENABLE;
        //根据产品参数查询数量
        Integer productListCount = productMapper.selectCountByParamList(minPrice,maxPrice,productTypeId,status);

        return productListCount;
    }


}
